package com.thti.mecool.client.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.command.send.plan.PlanSend;
import com.thti.mecool.client.model.biz.PlanBizImpl;
import com.thti.mecool.client.model.biz.TaskBizImpl;
import com.thti.mecool.client.model.po.PlanClient;
import com.thti.mecool.client.model.po.Task;
import com.thti.mecool.client.util.TimeUtil;
import com.thti.mecool.client.widget.ListWidget;
import com.thti.mecool.client.widget.ProgressDialogWidget;
import com.thti.mecool.client.widget.Toolbar;

public class TaskActivity extends BaseActivity {
	private Toolbar toolbar;
	private ExpandableListView undoneTask;
//	private Button SyncBtn;
	private Button Sync_upLoad;
	private Button Sync_cancel;
	private ListWidget doneTask;
	private TextView mecool_tabText;
	private ArrayList<TextView> tabtextlist = new ArrayList<TextView>();
	private ArrayList<ArrayList<Integer>> stat = new ArrayList<ArrayList<Integer>>();
	private ArrayList<Integer> statGroup = new ArrayList<Integer>();
	private ArrayList<String> listTag = new ArrayList<String>();
	private ArrayList<ArrayList<HashMap<String, String>>> taskList = new ArrayList<ArrayList<HashMap<String, String>>>();
	private ProgressDialogWidget pd;
	private ListWidget lw;
	private ArrayList<String> ProjectIds,PlanIds,StoreCodes,StoreNames,taskIds,taskNames;
	private boolean echo;
	PlanBizImpl planBizImpl;
	TaskBizImpl taskBizImpl;
	private Runnable r = new Runnable() {
		@Override
		public void run() {
			if (getDataFlag(HandlerConstant.PlanCommand)) {
				initSql();
				if (pd.isShowing()) {
					pd.dismiss("获取到数据！");
				}
				handler.removeCallbacks(r);
			} else {
				handler.postDelayed(r, 1000);
			}
		}
	};
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Cache.add(this);
		this.noTitle();
		setContentView(R.layout.mecool_taskmanage);
		ProjectIds = new ArrayList<String>();
		PlanIds=new ArrayList<String>();
		StoreCodes=new ArrayList<String>();
		StoreNames=new ArrayList<String>();
		taskIds=new ArrayList<String>();
		taskNames=new ArrayList<String>();
		handler = new Handler();
		initSql();
		 PlanSend.getPlan(getCurrentUser().getLoginName(),TimeUtil.dateToYear());
//		PlanSend.getPlan(getCurrentUser().getLoginName(), "2012-07-09");
		pd = new ProgressDialogWidget(this);
		pd.setDismissTime(45);
		TabHost mecool_taskHost = (TabHost) findViewById(R.id.mecool_taskHost);
		mecool_taskHost.setup();
		mecool_taskHost.addTab(mecool_taskHost.newTabSpec("undonetask")
				.setIndicator(createTab("待办任务")).setContent(R.id.undone_task));
		tabtextlist.get(0).setTextColor(Color.WHITE);
		mecool_taskHost.addTab(mecool_taskHost.newTabSpec("donetask")
				.setIndicator(createTab("已完成任务"))
				.setContent(R.id.mecool_done_task));
		mecool_taskHost.setOnTabChangedListener(new myOnTabChangedListener());
//		SyncBtn = (Button) findViewById(R.id.mecool_SyncBtn);
		Sync_upLoad = (Button) findViewById(R.id.mecool_Sync_upload);
		Sync_cancel = (Button) findViewById(R.id.mecool_Sync_cancel);
//		SyncBtn.setOnClickListener(new TaskOnClickListener());
		Sync_cancel.setOnClickListener(new TaskOnClickListener());
		handler.post(r);
	}

	private void initSql() {
		clearList();
		planBizImpl = new PlanBizImpl(this);
		List<PlanClient> PlanClients = planBizImpl.findByType(TimeUtil.dateToYear());
		int i=1;
		for (PlanClient pc : PlanClients) {
			if (pc != null) {
				taskBizImpl = new TaskBizImpl(this);
				if (pc.getPlanId() != null) {
					List<Task> tasks = taskBizImpl.findByprojectId(
							pc.getPlanId(), pc.getType(),0,String.valueOf(getCurrentUser().getId()));
					if (tasks != null) {
						foreachTask(tasks, pc.getType(),pc.getPlanId());
						if (lw == null)
							lw = new ListWidget(TaskActivity.this, taskList,
									listTag);
						else {
							lw.listRefurbish();
							lw.listExtra(listTag);
						}
						lw.setPlanIdAndProjectIds(PlanIds, ProjectIds,StoreCodes,StoreNames,taskIds,taskNames);
					}
				}
			}
			i++;
		}

	}
	private void clearList(){
		taskList.clear();
		listTag.clear();
		PlanIds.clear();
		ProjectIds.clear();
		StoreCodes.clear();
		StoreNames.clear();
		taskIds.clear();
		taskNames.clear();
	}
	
	
	private void foreachTask(List<Task> tasks, String type, String planId) {
		for (Task task : tasks) {
			ArrayList<HashMap<String, String>> proj = new ArrayList<HashMap<String, String>>();
			HashMap<String, String> t = new HashMap<String, String>();
			t.put("name", task.getTaskName());
			t.put("time", task.getStartTime() + " - " + task.getEndTime());
			t.put("addr", task.getStoreName());
			t.put("isType", type);
			proj.add(t);
				PlanIds.add(planId);
				listTag.add(task.getProjectName());
				taskList.add(proj);
				taskIds.add(task.getTaskId());
				ProjectIds.add(task.getProjectId());
				StoreCodes.add(task.getStoreId());
				StoreNames.add(task.getStoreName());
				taskNames.add(task.getTaskName());
		}
	}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	super.onActivityResult(requestCode, resultCode, data);
	System.out.println("resultCode    :  "+(requestCode==RESULT_OK));
	if(requestCode==RESULT_OK)
		echo=true;
	else
		echo=false;
}
	class TaskOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.mecool_SyncBtn:
//				SyncBtn.setVisibility(8);
				Sync_upLoad.setVisibility(0);
				Sync_cancel.setVisibility(0);
				BaseActivity.IsSyncEcho = false;
				doneTask.listRefurbish();
				break;
			case R.id.mecool_Sync_cancel:
//				SyncBtn.setVisibility(0);
				Sync_upLoad.setVisibility(8);
				Sync_cancel.setVisibility(8);
				BaseActivity.IsSyncEcho = true;
				doneTask.listRefurbish();
				break;
			default:
				break;
			}
		}
	}

	OnClickListener MyOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.mecool_toolbar_rightbtn:
				Intent i = new Intent(TaskActivity.this,
						TaskdoneDetailActivity.class);
				Bundle data = new Bundle();
				data.putSerializable("Tasklist", taskList);
				data.putSerializable("ListTag", listTag);
				i.putExtras(data);
				startActivity(i);
				break;

			default:
				finish();
				break;
			}
		}
	};

	class myOnTabChangedListener implements OnTabChangeListener {
		@Override
		public void onTabChanged(String tabId) {
			FrameLayout fl = (FrameLayout) findViewById(R.id.mecool_SyncBtn_framelayout);
			for (TextView tv : tabtextlist) {
				if (tv.isSelected()) {
					tv.setTextColor(Color.WHITE);
				} else {
					tv.setTextColor(Color.GRAY);
				}
			}
			if (tabId.equals("donetask")) {
				toolbar.setimage(Toolbar.right_btn,
						R.drawable.mecool_uncompleted_task_mark);
				Toolbar.hideRightButton();
				fl.setVisibility(0);
			} else {
				// toolbar.setimage(toolbar.right_btn, R.drawable.ic_launcher);
				toolbar.showRightButton();
				fl.setVisibility(8);
			}
		}
	}
 
	/**
	 * 自定义Tab标签的背景内容等
	 * 
	 * @param tabText
	 * @return
	 */
	public View createTab(String tabText) {
		View view = LayoutInflater.from(this).inflate(
				R.layout.mecool_task_tabindicator, null);
		mecool_tabText = (TextView) view.findViewById(R.id.mecool_tabText);
		mecool_tabText.setText(tabText);
		tabtextlist.add(mecool_tabText);
		return view;
	}

	@Override
	protected void onDestroy() {
		IsSyncEcho = true;
		if (getDataFlag(HandlerConstant.PlanCommand)) {
			removeDataFlag(HandlerConstant.PlanCommand);
		}
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if(echo){
			initSql();
			lw.listRefurbish();
		}else{
		toolbar = new Toolbar(this);
		Toolbar.left_btn.setOnClickListener(MyOnClickListener);
		Toolbar.right_btn.setOnClickListener(MyOnClickListener);
		toolbar.setimage(Toolbar.left_btn, R.drawable.mecool_go_back);
		toolbar.setToolbarCentreText("任务管理");
		toolbar.setimage(Toolbar.right_btn,
				R.drawable.mecool_uncompleted_task_mark);}
	}
}
